package edu.ccut.saturn.component;

import java.sql.Connection;
import java.util.Map;

/**
 * 平台提供的默认的验证组件类型，实现了<code>IValidate</code>接口，验证组件引用的java实现类都要继承这个类。
 * <p>
 * <li>字段validateKey：记录了验证组件的全局键值；
 * <li>字段errorInfos：记录了验证组件定义的错误信息。
 * 
 * @author 谷钰
 * @author 温建
 * 
 * @version 1.0 2008.9.03
 */
public abstract class DefaultSaturnValidate implements IValidate {

	private static final String LOGGER_KEY_BUNDLE_RUNTIME = SaturnLoggerManager.LOGGER_KEY_COMPONENT_RUNTIME;

	protected static ILogger logger = SaturnLoggerManager.getInstance()
			.getSaturnLogger(LOGGER_KEY_BUNDLE_RUNTIME);

	private String validateKey;

	private Map<String, String> errorInfos;

	/**
	 * 校验值未通过验证错误key
	 */
	public static final String _ERROR_ = "_error_"; //$NON-NLS-1$
	/**
	 * 参数值不合法错误key
	 */
	public static final String _ARGERROR_ = "_argError_"; //$NON-NLS-1$
	/**
	 * 输入校验值不合法错误key
	 */
	public static final String _VALUEERROR_ = "_valueError_"; //$NON-NLS-1$

	
	public DefaultSaturnValidate() {
	}

	public Map<String, String> getErrorInfos() {
		return errorInfos;
	}

	/**
	 * 根据errorKey查询错误信息 errorKey形如:_error_
	 * 
	 * @param errorKey
	 * @return
	 */
	public String getErrorInfo(String errorKey) {
		String resultErrorValue = null;
		if (errorKey != null && errorInfos != null) {
			resultErrorValue = errorInfos.get(errorKey);
		}
		return resultErrorValue;
	}

	public void setErrorInfos(Map<String, String> errorInfos) {
		this.errorInfos = errorInfos;
	}

	public String getValidateKey() {
		return validateKey;
	}

	public void setValidateKey(String validateKey) {
		this.validateKey = validateKey;
	}

	public void validate(Object value, Object[] args, ValidateResult result) {
		if (value == null) {
			result.addValidateError(Messages
					.getString("DefaultSaturnValidate.0"), value); //$NON-NLS-1$
		} else {
			doValidate(value, args, result);
		}
	}

	/**
	 * 获得数据库连接。根据bundle名称获得该bundle指定的数据库连接，用户负责关闭连接。
	 * 
	 * @return
	 */
	protected Connection getConnection() {

		if (this.validateKey != null) {
			int index = this.validateKey.indexOf("::"); //$NON-NLS-1$

			if (index > 0) {
				return DatabaseManager.getInstance().getConnection(
						this.validateKey.substring(0, index));
			}
		}
		return DatabaseManager.getInstance().getConnection();
	}

	protected void doValidate(Object value, Object[] args, ValidateResult result) {

	}

	/**
	 * 发送错误信息
	 * 
	 * @param errorKey
	 * @param value
	 * @param result
	 */
	public void sendError(String errorKey, Object value, ValidateResult result) {
		result.addValidateError(getErrorInfo(errorKey), value);
	}
}
